<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="35%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="应用名称" prop="app_name">
            <ElInput v-model="formData.app_name" placeholder="请输入应用名称" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="表名称" prop="table_name">
            <ElInput v-model="formData.table_name" placeholder="请输入表名称" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="表描述" prop="table_comment">
            <ElInput v-model="formData.table_comment" placeholder="请输入表描述" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="基础类名" prop="class_name">
            <ElInput v-model="formData.class_name" placeholder="请输入基础类名" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="Schema 名称" prop="schema_name">
            <ElInput v-model="formData.schema_name" placeholder="请输入 Schema 名称" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="基础文件名" prop="filename">
            <ElInput v-model="formData.filename" placeholder="请输入基础文件名" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="API 版本" prop="api_version">
            <ElInput v-model="formData.api_version" placeholder="请输入 API 版本" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="默认时间列" prop="default_datetime_column">
            <ElSwitch v-model="formData.default_datetime_column" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElFormItem label="代码生成路径" prop="gen_path">
        <ElInput v-model="formData.gen_path" placeholder="请输入代码生成路径" />
      </ElFormItem>
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElRow, ElCol } from 'element-plus'
import { createGenBusiness, updateGenBusiness } from '@/api/code_generator/gen_business'
import type { GenBusiness, GenBusinessCreate, GenBusinessUpdate } from '@/api/code_generator/gen_business'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: GenBusiness
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '新增业务' : '编辑业务'))

const formRef = ref<FormInstance>()

const getInitialFormData = (): GenBusinessCreate => ({
  app_name: '',
  table_name: '',
  table_comment: '',
  class_name: '',
  schema_name: '',
  filename: '',
  default_datetime_column: true,
  api_version: 'v1',
  gen_path: '',
  remark: ''
})

const formData = reactive<GenBusinessCreate | GenBusinessUpdate>(getInitialFormData())

const rules: FormRules = {
  app_name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  table_name: [{ required: true, message: '请输入表名称', trigger: 'blur' }]
}

const initFormData = () => {
  if (props.type === 'edit' && props.editData) {
    Object.assign(formData, props.editData)
  } else {
    Object.assign(formData, getInitialFormData())
  }
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      initFormData()
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: true }
)

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (props.type === 'add') {
        await createGenBusiness(formData as GenBusinessCreate)
        ElMessage.success('新增成功')
      } else {
        await updateGenBusiness(props.editData?.id || 0, formData as GenBusinessUpdate)
        ElMessage.success('更新成功')
      }
      emit('submit')
      dialogVisible.value = false
    } catch (error: any) {
      if (error?.response?.data?.detail?.includes('Duplicate entry')) {
        ElMessage.error('操作失败：表名称已存在，请使用其他名称。')
      } else {
        console.error(error)
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>